$(function () {
    $('.comment-btn').on('click', function () {
        $(this).parents('.forum-card-toolbar').next('.comment-content').collapse('toggle');
    });

    // 点赞、收藏、转发
    $('#forumContent').on('click', '.tool-list a', function () {
        var $this = $(this);
        var url;
        var id = $this.parents('.forum-card').find('input.user-forum-id').val();
        var type = $this.data('type');
        var flag = $this.hasClass('active');
        var icon = $this.find('i.mdi');

        // 收藏、点赞
        if (type == 2 || type == 1) {
            if (flag) {
                // 已收藏或点赞，执行取消操作
                url = '/userForumLike/delUserForumLike';
                icon.hasClass('mdi-thumb-up') && icon.removeClass('mdi-thumb-up').addClass('mdi-thumb-up-outline');
                icon.hasClass('mdi-star') && icon.removeClass('mdi-star').addClass('mdi-star-outline');
            } else {
                // 未收藏或点赞，执行操作
                url = '/userForumLike/addUserForumLike';
                icon.hasClass('mdi-thumb-up-outline') && icon.removeClass('mdi-thumb-up-outline').addClass('mdi-thumb-up');
                icon.hasClass('mdi-star-outline') && icon.removeClass('mdi-star-outline').addClass('mdi-star');
            }
            messageAction(type, id, url, function () {
                $this.toggleClass('active');
                var num = $this.find('span').html();
                flag ? num-- : num++;
                $this.find('span').html(num++);
            });
        }
    });

    $('#publishPic').on('change', function () {
        if (imgNum > 8) {
            promptInfo('最多只能上传9张图片');
            $('#publishPic').val('');
            return;
        }
        uploadImg(1);
    });
    $('#publishVideo').on('change', function () {
        uploadImg(2);
    });
    $('#imgBox').on('click', 'li i.mdi', function () {
        $(this).parents('li').remove();
        videoFlag = undefined;
        imgNum--;
    });

    $('#content').on('keyup', function () {
        var value = $(this).val();
        $('#publishBtn').prop('disabled', !value);
    })
    $(document).on('click', '.emoji_container li a', function () {
        setTimeout(function () {
            var value = $('#content').val();
            $('#publishBtn').prop('disabled', !value);
        }, 100)
    })
    $('#content').emoji({
        button: '#publishEmotIcon',
        showTab: true,
        animation: 'fade',
        basePath: '../../images/emoji',
        icons: emojiLists,
        adjoin: true
    });

    // 是否公开
    $('.publish-power').on('click', 'ul a', function () {
        var type = $(this).data('type');
        var label = $(this).find('span').html();
        $('#publishPower').data('type', type).find('span').html(label);
    });

    $('#publishBtn').on('click', function () {
        addForum();
        videoFlag = undefined;
    })

    // 优秀话题
    goodTopic();
    // 热力搜索
    mostSearch();

    // 帖子加载
    var pageIndex = 1;
    forumItem(pageIndex, 10);
    $(document).on('click', '.loading-more', function () {
        var pageSize = 10;
        pageIndex++
        forumItem(pageIndex, pageSize);
    });

    // iframe打开tab
    $(document).on('click', '.topic-link', function() {
        parent.$(parent.document).data('multitabs').create({
            iframe : true,
            title : $(this).data('title') ? $(this).data('title') : '热门话题',
            url : $(this).data('url') ? $(this).data('url') : 'lyear-main.html'
        }, true);
    });
});

/**
 * 功能：个人信息
 * */
function forumInfo() {
    $.ajax({
        url: '/userForum/selectLoginUserForumInfo',
        type: 'post',
        dataType: "json",
        data: {
            accountId: null
        },
        success: function (data) {
            if (data.code == '000000') {
                /*
                * fansCount         | int    | 粉丝数量
                * forumCount        | int    | 发布论坛数量
                * userImg           | String | 头像
                * userName          | String | 名称
                * userLevel         | int    | 用户等级
                * createUserApprove | int    | 是否V认证 目前写死只返回0
                * */
                console.log('个人信息数据：', data.data);
            } else {
                promptInfo('错误代码：' + data.code);
            }
        },
        error: function (res) {
            promptInfo('数据请求失败，请重试！(' + res + ')');
        }
    })
}

/**
* 功能：发布帖子
* */
var videoFlag;
function addForum() {
    var imgFlag = false;
    var forumContent = $('#content').val();
    var attachmentUploadId1 = '';
    var forumType =  $('#publishPower').data('type');
    var jsonData = {
        "forumContent": forumContent,           // 内容
        "forumType":forumType,                  // 是否公开 0是 1否
    };
    if ($('#imgBox li').hasClass('video-preview')) {
        jsonData.attachmentUploadId1 = $('#imgBox video').data('fileid');
        videoFlag = true;
    } else {
        $('#imgBox li').each(function (index, item) {
            // jsonData['attachmentUploadId' + (index + 1)] = $(item).find('img').prop('src');
            jsonData['attachmentUploadId' + (index + 1)] = $(item).find('img').data('fileid');
        });
    }
    if (!forumContent && !jsonData.attachmentUploadId1) {
        promptInfo('发布内容不能为空！');
        return;
    }
    $.ajax({
        url: '/userForum/addUserForum',
        type: 'post',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: function (data) {
            if (data.code == '000000') {
                // 清除发布框内容
                $('#content').val('');
                $('#imgBox').slideUp(160).empty();
                $('#publishBtn').prop('disabled', true);

                // 新发布内容填充
                var listData = data.data;

                // 标题
                var regex = /\#(.+?)\#/g;
                var contentText = listData.forumContent;
                var hotTitleArr = contentText.match(regex);
                if (hotTitleArr) {
                    for (let i = 0; i < hotTitleArr.length; i++) {
                        var hotTag = hotTitleArr[i];
                        contentText = contentText.replace(hotTag, '<a href="#" class="topic-link">' + hotTag + '</a>');
                    }
                }

                var imgDom = '';
                var imgNum = 0;
                if (videoFlag) {
                    imgDom = '<div class="list video-show"><video controls src="' + listData.attachmentUploadId1 + '"></video></div>';
                } else {
                    for (let j = 0; j < 9; j++) {
                        var src = listData['attachmentUploadId' + (j + 1)];
                        if (src == null) {
                            break;
                        }
                        imgNum++;
                        imgDom += '<div class="list"><img src="' + listData['attachmentUploadId' + (j + 1)] + '"></div>';
                    }
                }

                var listDom = `
                        <div class="card forum-card" style="display: none;">
                            <input type="text" value="${listData.userForumId}" class="hide user-forum-id">
                            <div class="forum-card-header">
                                <div class="head"><a href="#"><img src="${userImg}" alt=""></a></div>
                                <h5><a href="#">${userName}</a><span>LV${userLevel}</span></h5>
                                <p><span>${new Date(listData.createTm).Format("yyyy-MM-dd")}</span><span>0次阅读</span></p>
                            </div>
                            <div class="forum-card-body">
                                <div class="detail-text">${contentText}</div>
                                <div class="detail-photo img-col-${imgNum}">${imgDom}</div>
                            </div>
                            <div class="forum-card-toolbar clearfix">
                                <div class="tool-list"><a href="JavaScript:void(0);" data-type="3"><i class="mdi mdi-open-in-new"></i><span>0</span></a></div>
                                <div class="tool-list"><a href="JavaScript:void(0);" data-type="2"><i class="mdi mdi-star-outline"></i>收藏</a></div>
                                <div class="tool-list"><a href="JavaScript:void(0);" class="comment-btn" onclick="forumReply(this, '${listData.userForumId}', '${listData.replyCount}')"><i class="mdi mdi-message-text-outline"></i><span>0</span></a></div>
                                <div class="tool-list"><a href="JavaScript:void(0);" data-type="1"><i class="mdi mdi-thumb-up-outline"></i><span>0</span></a></div>
                            </div>
                        </div>`;
                $('#forumContent').prepend(listDom).find('.forum-card').slideDown(160);
                // 表情回显
                emojiShow('.detail-text');

                $('.detail-photo').viewer({
                    title: false,
                });
            } else {
                promptInfo('错误代码：' + data.code);
            }
        },
        error: function (res) {
            promptInfo('数据请求失败，请重试！(' + res + ')');
        }
    })
}

/**
 * 功能：上传图片
 * */
// 图片计数
var imgNum = 0;
function uploadImg(type) {
    let fileToUpLoad;
    if (type == 2) {
        // 视频
        fileToUpLoad = $('#publishVideo').prop('files')[0];
    } else {
        // 图片
        fileToUpLoad = $('#publishPic').prop('files')[0];
    }
    var formFile = new FormData();
    formFile.append("file", fileToUpLoad);
    var data = formFile;
    $.ajax({
        url: '/file/uploadByOneFile',
        data: data,
        type: "POST",
        dataType: "json",
        async: false,
        cache: false,
        processData: false,
        contentType: false,
        success: function (data) {
            if (data.code == "000000") {
                var labelNode;
                if (type == 2) {
                    // 视频
                    $('#publishVideo').val('');
                    labelNode = '<li class="video-preview"><video controls src="' + data.data.accessUrl + '" data-fileId="' + data.data.fileId + '"></video><i class="mdi mdi-close"></i></li>';
                } else {
                    $('#publishPic').val('');
                    labelNode = '<li><img src="' + data.data.accessUrl + '" data-fileId="' + data.data.fileId + '"><i class="mdi mdi-close"></i></li>';
                }
                $('#imgBox').append(labelNode);
                imgNum++;
            } else {
                promptInfo('错误代码：' + data.code);
            }
        },
        error: function (res) {
            promptInfo('数据请求失败，请重试！(' + res + ')');
        }
    });
}

/**
 * 功能：加载帖子数据
 * 参数：config-调用自身  offset-已加载数据数量(初始为0)  size-每次请求数据数量
 * */
function forumItem(pageIndex, pageSize) {
    $.ajax({
        url: '/userForum/userForumListPage',
        type: 'get',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: {
            userForumId: '',        // 论坛id
            forumTitle: '',         // 标题（根据标题查询）
            forumContent: '',       // 内容（根据内容查询，不知有没有这个功能先预留了）
            userName: '',           // 用户名（根据用户名查询）
            accountId: '',          // 用户id（查询用户所有的论坛，个人主页时调用）

            pageIndex: pageIndex,
            pageSize: pageSize,
            sortName: 'createTm',
            sortOrder: 'desc'
        },
        success: function (data) {
            if (data.code == '000000') {
                var itemsData = data.data;      // 帖子数据集合
                var items = '';                 // 帖子Dom集合

                if (itemsData.length != 0) {
                    for (var i = 0; i < itemsData.length; i++) {
                        items += itemDom(itemsData[i]);
                    }
                    // 数据不为空时，加载数据结构
                    if ((pageIndex * pageSize) >= data.totalRecords){
                        // 已有数据数量 + 请求数据数量 >= 所有数据时，加载全部数据，隐藏加载更多按钮
                        console.log('没有数据了');
                        $(".loading-more").hide();
                        // config.isEnd = true; // 停止滚动加载请求
                    }else{
                        // 已有数据数量 + 请求数据数量 < 所有数据时，加载新请求的数据
                        console.log('有更多数据');
                        $(".loading-more").show();
                    }
                } else {
                    // 数据为空时，提示暂无数据
                    $('#forumContent').html('<p class="nodata">暂无帖子</p>');
                    $(".loading-more").hide();
                }

                $('#forumContent').append(items);
                // 表情回显
                emojiShow('.detail-text');

                $('.detail-photo').viewer({
                    title: false,
                });
            } else {
                promptInfo('错误代码：' + data.code);
            }
        },
        error: function (res) {
            promptInfo('数据请求失败，请重试！(' + res + ')');
        }
    })
}

/**
 * 功能：帖子数据结构
 * */
function itemDom(data) {
    // 标题处理，截取热话字段拼成链接
    var regex = /\#(.+?)\#/g;
    var contentText = data.forumContent;
    var hotTitleArr = contentText.match(regex);
    if (hotTitleArr) {
        for (let i = 0; i < hotTitleArr.length; i++) {
            var hotTag = hotTitleArr[i];
            contentText = contentText.replace(hotTag, '<a href="#!" data-url="/搜索页面链接/?forumTitle=' + hotTag.slice(1, hotTag.length - 1) + '" class="topic-link js-create-tab">' + hotTag + '</a>');
        }
    }

    // 图片
    var imgDom = '';
    var imgNum = 0;
    for (let i = 0; i < 9; i++) {
        var src = data['attachmentUploadId' + (i + 1)];
        if (src == null) {
            break;
        }
        imgNum++;
        imgDom += '<div class="list"><img src="' + data['attachmentUploadId' + (i + 1)] + '"></div>';
    }

    var deleteForumBtn = '';
    if (accountId == data.createPeopleId) {
        deleteForumBtn = `<a href="#!" class="delete" onclick="deleteForum(this, '${data.userForumId}');"><i class="mdi mdi-delete"></i>删除</a>`;
    }

    var listDom = `
            <div class="card forum-card">
                <input type="text" value="${data.userForumId}" class="hide user-forum-id">
                ${deleteForumBtn}
                <div class="forum-card-header">
                    <div class="head"><a href="#"><img src="${data.createUerImg}" alt=""></a></div>
                    <h5><a href="#">${data.createPeopleName}</a><span>LV${data.userLevel}</span></h5>
                    <p><span>${data.createTm}</span><span>${data.readNumber}次阅读</span></p>
                </div>
                <div class="forum-card-body">
                    <div class="detail-text">${contentText}</div>
                    <div class="detail-photo img-col-${imgNum}">${imgDom}</div>
                </div>
                <div class="forum-card-toolbar clearfix">
                    <div class="tool-list"><a href="JavaScript:void(0);" data-type="3"><i class="mdi mdi-open-in-new"></i><span>${data.shiftCount}</span></a></div>
                    <div class="tool-list"><a href="JavaScript:void(0);" data-type="2" ${data.isCollect > 0 ? 'class="active"' : ''}><i ${data.isCollect > 0 ? 'class="mdi mdi-star"' : 'class="mdi mdi-star-outline"'}></i>收藏</a></div>
                    <div class="tool-list"><a href="JavaScript:void(0);" class="comment-btn" onclick="forumReply(this, '${data.userForumId}', '${data.replyCount}')"><i class="mdi mdi-message-text-outline"></i><span>${data.replyCount}</span></a></div>
                    <div class="tool-list"><a href="JavaScript:void(0);" data-type="1" ${data.isLike > 0 ? 'class="active"' : ''}><i ${data.isLike > 0 ? 'class="mdi mdi-thumb-up"' : 'class="mdi mdi-thumb-up-outline"'}></i><span>${data.likeCount}</span></a></div>
                </div>
            </div>`;
    return listDom;
}

/**
 * 功能：查看评论
 * */
function forumReply(el, userForumId, replyCount) {
    var replyFlag = $('#' + userForumId).length;
    var $this = $(el);
    var $showNum = 16;
    var jsonData = {
        userForumId,

        pageSize: $showNum,
        pageIndex: 1,
        sortName: 'createTm',
        sortOrder: 'desc'
    };
    if (!replyFlag) {
        var commentBox =
            `
                <div class="comment-content collapse" id="${userForumId}">
                    <div class="comment-reply clearfix">
                        <div class="head"><img src="${userImg}" alt=""></div>
                        <textarea class="form-control"></textarea>
                        <div class="dropdown pull-left reply-emoticon">
                            <a href="JavaScript:void(0);" class="emotion-btn" id="emotion-btn-${userForumId}">
                                <i class="mdi mdi-emoticon"></i>表情
                            </a>
                        </div>
                        <!--<label class="pull-left reply-pic">
                            <input type="file" accept="image/*" class="hide">
                            <i class="mdi mdi-image"></i>图片
                        </label>-->
                        <button type="button" onclick="addForumReply(this, '${jsonData.userForumId}')" class="btn btn-forum pull-right" disabled>发布</button>
                    </div>
                    <div class="comment-list">
                        <div class="reply-num" style="display: none;"><span>当前已经评论<span class="span-num">${replyCount}</span>次</span></div>
                        <!--<div class="comment-loading"><i class="mdi mdi-36px mdi-spin mdi-loading"></i></div>-->
                    </div>
                </div>
            `;

        $this.parents('.forum-card-toolbar').after(commentBox);

        var $commentBody = $('#' + userForumId);
        $commentBody.slideDown(100, function () {
            $commentBody.find('textarea').emoji({
                button: '#emotion-btn-' + userForumId,
                showTab: true,
                animation: 'fade',
                basePath: '../../images/emoji',
                icons: emojiLists,
                adjoin: true
            });
            $commentBody.find('textarea').on('keyup', function () {
                var value = $(this).val();
                $commentBody.find('button.btn-forum').prop('disabled', !value);
            })
            $(document).on('click', '.emoji_container li a', function () {
                setTimeout(function () {
                    var value = $commentBody.find('textarea').val();
                    $commentBody.find('button.btn-forum').prop('disabled', !value);
                }, 100)
            })
        });

        $.ajax({
            url: '/userForumReply/selectForumReply',
            type: 'post',
            dataType: "json",
            data: jsonData,
            success: function (data) {
                if (data.code == '000000') {
                    /*$commentBody.find('.comment-loading').slideUp(10, function () {
                        $(this).remove();
                    });*/
                    var replyListData = data.data;
                    replyListData.length && $commentBody.find('.reply-num').show();
                    var replyListHtml = '';
                    // var deleteReply = `<a href="Javascript:void(0);" onclick="deleteReply(this, '${userForumReplyId}');"><i class="mdi mdi-delete-variant"></i>删除</a>`;
                    for (let i = 0; i < replyListData.length; i++) {
                        if (i > 4) {
                            break;
                        }
                        var replayBox = '';
                        if (replyListData[i].sonReplyList.length > 0) {
                            var list = '';
                            var listMore = '';
                            for (let j = 0; j < replyListData[i].sonReplyList.length; j++) {    // 循环子评论
                                if (replyListData[i].sonReplyList.length > 4 && j > 1) {
                                    break;
                                }

                                var deleteReply = '';
                                if (replyListData[i].sonReplyList[j].createPeopleId == accountId) {
                                    deleteReply = `<a href="Javascript:void(0);" onclick="deleteReply(this, '${replyListData[i].sonReplyList[j].userForumReplyId}');"><i class="mdi mdi-delete-variant"></i>删除</a>`;
                                }

                                var replyName = '';
                                if (replyListData[i].sonReplyList[j].replyLevel > 2) {
                                    replyName = '<a href="#">@' + replyListData[i].sonReplyList[j].replyName + '</a>';
                                }
                                list +=
                                    `
                                    <div class="list-info" data-id="${replyListData[i].sonReplyList[j].userForumReplyId}">                                    
                                        <input type="text" value="${replyListData[i].sonReplyList[j].userForumReplyId}" data-userforumid="${jsonData.userForumId}" data-level="${replyListData[i].sonReplyList[j].replyLevel}" data-replypid="${replyListData[i].sonReplyList[j].userForumReplyId}" class="hide">
                                        <p><a href="#">${replyListData[i].sonReplyList[j].createPeopleName}：</a>${replyName} ${replyListData[i].sonReplyList[j].replyContent}</p>
                                        <div class="list-time">${replyListData[i].sonReplyList[j].createTm}</div>
                                        <div class="list-action">
                                            <a href="Javascript:void(0);" class="list-reply-btn"><i class="mdi mdi-message-text-outline"></i>回复</a>
                                            ${deleteReply}
                                            <!--<a href="Javascript:void(0);"><i class="mdi mdi-thumb-up-outline"></i><span>6</span></a>-->
                                        </div>
                                    </div>
                                    `;
                            }
                            if (replyListData[i].sonReplyList.length > 4) {
                                listMore = '<div class="reply-list-more" onclick="replyModal(this, \'' + replyListData[i].userForumReplyId + '\', \'' + jsonData.userForumId + '\');">查看更多回复<i class="mdi mdi-menu-down"></i></div>';
                            }
                            // 子评论
                            replayBox = list + listMore;
                        }

                        var deleteReply = '';
                        if (replyListData[i].createPeopleId == accountId) {
                            deleteReply = `<a href="Javascript:void(0);" onclick="deleteReply(this, '${replyListData[i].userForumReplyId}', true);"><i class="mdi mdi-delete-variant"></i>删除</a>`;
                        }

                        // 一级评论
                        replyListHtml += `
                            <div class="list" data-id="${replyListData[i].userForumReplyId}">
                                <div class="head"><a href="#"><img src="${replyListData[i].userImg}" alt=""></a></div>
                                <div class="list-info" data-id="${replyListData[i].userForumReplyId}">
                                    <input type="text" value="${replyListData[i].userForumReplyId}" data-userforumid="${jsonData.userForumId}" data-level="${replyListData[i].replyLevel}" data-replypid="${replyListData[i].userForumReplyId}" class="hide one-reply-id">
                                    <p><a href="#">${replyListData[i].createPeopleName}：</a>${replyListData[i].replyContent}</p>
                                    <div class="list-time">${replyListData[i].createTm}</div>
                                    <div class="list-action">
                                        <a href="Javascript:void(0);" class="list-reply-btn"><i class="mdi mdi-message-text-outline"></i>回复</a>
                                        ${deleteReply}
                                        <!--<a href="Javascript:void(0);"><i class="mdi mdi-thumb-up-outline"></i><span>6</span></a>-->
                                    </div>
                                </div>
                                <div class="replay-box">${replayBox}</div>
                                
                                <!--<div class="replay-box">
                                    <div class="list-info">
                                        <p><a href="#">用户名：</a>盖茨拥有微软1.37％的流通股，价值超过260亿美元；</p>
                                        <div class="list-time">2021.05.12 08:32</div>
                                        <div class="list-action">
                                            <a href="Javascript:void(0);">回复</a>
                                            <a href="Javascript:void(0);"><i class="mdi mdi-thumb-up-outline"></i><span>6</span></a>
                                        </div>
                                    </div>
                                    <div class="list-info">
                                        <p><a href="#">用户名：</a>梅琳达盖茨基金会拥有超510亿美元资产，还有其他投资和不动产等。L老板联播的微博视频上都直播并声明了</p>
                                        <div class="list-time">2021.05.12 08:32</div>
                                        <div class="list-action">
                                            <a href="Javascript:void(0);">回复</a>
                                            <a href="Javascript:void(0);"><i class="mdi mdi-thumb-up-outline"></i><span>6</span></a>
                                        </div>
                                    </div>
                                    <div class="list-info">
                                        <p><a href="#">用户名：</a>盖茨拥有微软1.37％的流通股，价值超过260亿美元；梅琳达盖茨基金会拥有超510亿美元资产，还有其他投资和不动产等。L老板联播的微博视频上都直播并声明了</p>
                                        <div class="list-time">2021.05.12 08:32</div>
                                        <div class="list-action">
                                            <a href="Javascript:void(0);">回复</a>
                                            <a href="Javascript:void(0);"><i class="mdi mdi-thumb-up-outline"></i><span>6</span></a>
                                        </div>
                                    </div>
                                    <div class="replay-more"><a href="#">共<span>15</span>条回复 <i class="mdi mdi-menu-down"></i></a></div>
                                </div>-->
                            </div>
                        `
                    }

                    if (data.totalRecords > 5) {
                        replyListHtml += '<div class="reply-more"><a href="#!">查看更多<i class="mdi mdi-chevron-right"></i></a></div>';
                    }

                    $commentBody.find('.comment-list').append(replyListHtml);
                    // 表情回显
                    emojiShow('.list-info');

                    $(document).on('click', '.list-info .list-reply-btn', function () {
                        var userName = $(this).parents('.list-info').children('p').find('a').html().slice(0, -1);
                        $('#replyModal').modal('show');
                        $('#replyModal h4 span').html(' @' + userName);

                        var parentDom = $(this).parents('.list-info');
                        var replyLevel = parentDom.children('input').data('level') + 1;
                        replyLevel > 3 ? replyLevel = 3 : '';

                        $('#oneReplyId').val(parentDom.parents('.list').find('input.one-reply-id').val());
                        $('#forumId').val(parentDom.children('input').data('userforumid'));
                        $('#replyLevel').val(replyLevel);
                        $('#replyPid').val(parentDom.children('input').data('replypid'));
                        $('#replyId').val(parentDom.attr('id'));

                    })
                } else {
                    promptInfo('错误代码：' + data.code);
                }
            },
            error: function (res) {
                promptInfo('数据请求失败，请重试！(' + res + ')');
            }
        })
    } else {
        var $commentBody = $('#' + userForumId);
        $commentBody.slideUp(100, function () {
            $(this).remove();
        });
    }
}

/**
 * 功能：查看子评论
 * */
function replyModal(el, userForumReplyId, userForumId) {
    var $this = $(el);
    var $headDom = $this.parents('.list').children('.head').prop('outerHTML');
    var $listInfo = $this.parents('.list').children('.list-info').prop('outerHTML');
    var replayBox = '<div class="replay-box" id="replyBox"></div>';
    var moreBtn = '<div class="reply-more2"><a href="#!">查看更多<i class="mdi mdi-menu-down"></i></a></div>';

    var replyDome = '<div class="list">' + $headDom + $listInfo + replayBox + '</div>' + moreBtn;

    $('#moreReplyModal').modal('show');
    $('#replyBody').html(replyDome);


    $.loadmore.get(action, {
        scroll: false,  // 默认是false,是否支持滚动加载
        size: 10,       // 默认是10
        more: '.reply-more2'
    });
    function action(config, offset, size) {
        console.log(offset, size)
        config.isAjax = true;

        var jsonData = {
            userForumReplyId,
            userForumId,

            pageSize: '',
            pageIndex: 1,
            sortName: 'createTm',
            sortOrder: 'desc'
        };
        $.ajax({
            url: '/userForumReply/selectForumSonReply',
            type: 'post',
            dataType: "json",
            data: jsonData,
            success: function (data) {
                if (data.code == '000000') {
                    var replyListData = data.data;
                    var replayBox = '';         // 子评论盒子

                    $('#moreReplyModal h4 span').html(replyListData.sonReplyList.totalRecords);

                    if ((offset + size) >= replyListData.sonReplyList.list.length){
                        // 已有数据数量 + 请求数据数量 >= 所有数据时，加载全部数据，隐藏加载更多按钮
                        for (var i = offset; i < replyListData.sonReplyList.list.length; i++) {
                            replayBox += replyListDom(replyListData.sonReplyList.list[i], userForumId);
                        }
                        console.log('没有数据了');
                        $(".reply-more2").hide();
                        config.isEnd = true; // 停止滚动加载请求
                    }else{
                        // 已有数据数量 + 请求数据数量 < 所有数据时，加载新请求的数据
                        for (var i = offset; i < (offset + size); i++) {
                            replayBox += replyListDom(replyListData.sonReplyList.list[i], userForumId);
                        }
                        console.log('有更多数据');
                        $(".reply-more2").show();
                    }
                    $('#replyBox').append(replayBox);

                    // 表情回显
                    emojiShow('.list-info');

                    $(document).on('click', '.list-info .list-reply-btn', function () {
                        var userName = $(this).parents('.list-info').children('p').find('a').html().slice(0, -1);
                        $('#replyModal').modal('show');
                        $('#replyModal h4 span').html(' @' + userName);

                        var parentDom = $(this).parents('.list-info');
                        var replyLevel = parentDom.children('input').data('level') + 1;
                        replyLevel > 3 ? replyLevel = 3 : '';

                        $('#oneReplyId').val(parentDom.parents('.list').find('input.one-reply-id').val());
                        $('#forumId').val(parentDom.children('input').data('userforumid'));
                        $('#replyLevel').val(replyLevel);
                        $('#replyPid').val(parentDom.children('input').data('replypid'));
                        $('#replyId').val(parentDom.attr('id'));

                    })
                } else {
                    promptInfo('错误代码：' + data.code);
                }
            },
            error: function (res) {
                promptInfo('数据请求失败，请重试！(' + res + ')');
            }
        })
    }
}


/**
 * 功能：更多回复弹窗数据结构
 * */
function replyListDom(data, userForumId) {
    var list = '';
    var replyName = '';
    if (data.replyLevel > 2) {
        replyName = '<a href="#">@' + data.replyName + '</a>';
    }
    var deleteReply = '';
    if (data.createPeopleId == accountId) {
        deleteReply = `<a href="Javascript:void(0);" onclick="deleteReply(this, '${data.userForumReplyId}');"><i class="mdi mdi-delete-variant"></i>删除</a>`;
    }
    list +=
        `
            <div class="list-info" data-id="${data.userForumReplyId}">
                <input type="text" value="${data.userForumReplyId}" data-userforumid="${userForumId}" data-level="${data.replyLevel}" data-replypid="${data.userForumReplyId}" class="hide">
                <p><a href="#">${data.createPeopleName}：</a>${replyName} ${data.replyContent}</p>
                <div class="list-time">${data.createTm}</div>
                <div class="list-action">
                    <a href="Javascript:void(0);" class="list-reply-btn"><i class="mdi mdi-message-text-outline"></i>回复</a>
                    ${deleteReply}
                    <!--<a href="Javascript:void(0);"><i class="mdi mdi-thumb-up-outline"></i><span>6</span></a>-->
                </div>
            </div>
        `;

    return list;
}


/**
 * 功能：发布评论
 * */
function addForumReply(el, forumId) {
    var commentList = $(el).parent().next('.comment-list');
    var replyContent = $(el).parent().find('textarea').val();
    if (!replyContent) {
        promptInfo('评论内容不能为空！');
        return;
    }
    var replyData = {
        forumId,                // 论坛id
        replyLevel: 1,          // 评论等级 1.一级 2.二级 3.三级
        replyPid: '0',          // 评论父id（二级父id是一级评论的id，三级父id是 XXX2评论的id  （XXX1回复XXX2）一级传0或null）
        replyContent,           // 评论内容
    }
    $.ajax({
        url: '/userForumReply/addForumReply',
        type: 'post',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(replyData),
        success: function (data) {
            if (data.code == '000000') {
                $(el).parent().find('textarea').val('');
                $(el).parent().find('.btn-forum').prop('disabled', true);
                commentList.find('.reply-num').show();

                // 当前评论次数增加
                var numSpan = commentList.find('.reply-num .span-num');
                var num = numSpan.html();
                numSpan.html(num++);


                var time = new Date(new Date()).Format("yyyy-MM-dd hh:mm");
                var html = `
                        <div class="list" data-id="${data.data.userForumReplyId}" style="display: none;">
                            <div class="head"><a href="#"><img src="${userImg}" alt=""></a></div>
                            <div class="list-info" data-id="${data.data.userForumReplyId}">
                                <input type="text" value="${data.data.userForumReplyId}" data-userforumid="${data.data.forumId}" data-level="${data.data.replyLevel}" data-replypid="${data.data.userForumReplyId}" class="hide one-reply-id">
                                <p><a href="#">${userName}：</a>${replyData.replyContent}</p>
                                <div class="list-time">${time}</div>
                                <div class="list-action">
                                    <a href="Javascript:void(0);" class="list-reply-btn"><i class="mdi mdi-message-text-outline"></i>回复</a>
                                    <a href="#!" class="delete" onclick="deleteReply(this, '${data.data.userForumId}');"><i class="mdi mdi-delete-variant"></i>删除</a>
                                    <!--<a href="Javascript:void(0);"><i class="mdi mdi-thumb-up-outline"></i><span>0</span></a>-->
                                </div>
                            </div>    
                            <div class="replay-box"></div>    
                        </div>
                `
                commentList.find('.reply-num').after(html);
                commentList.find('.reply-num').next('.list').slideDown(160);
                // 表情回显
                emojiShow('.list-info p');
            } else {
                promptInfo('错误代码：' + data.code);
            }
        },
        error: function (res) {
            promptInfo('数据请求失败，请重试！(' + res + ')');
        }
    })
}

/**
 * 功能：发布二级评论
 * */
function addForumReply2() {

    var id = $('#oneReplyId').val();

    var replyData = {
        forumId: $('#forumId').val(),                // 论坛id
        replyLevel: $('#replyLevel').val(),          // 评论等级 1.一级 2.二级 3.三级
        replyPid: $('#replyPid').val(),              // 评论父id（二级父id是一级评论的id，三级父id是 XXX2评论的id  （XXX1回复XXX2）一级传0或null）
        replyContent: $('#replyContent').val(),      // 评论内容
        oneReplyId: $('#oneReplyId').val(),          // 一级评论的id
    }
    $.ajax({
        url: '/userForumReply/addForumReply',
        type: 'post',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(replyData),
        success: function (data) {
            if (data.code == '000000') {
                var backData = data.data;
                var time = new Date(new Date()).Format("yyyy-MM-dd hh:mm");
                // var listReplyBox = $('#' + id).next('.replay-box');
                var listReplyBox = $('.list-info[data-id="' + id + '"]').next('.replay-box');

                var replyName = '';
                if (replyData.replyLevel > 2) {
                    replyName = '<a href="#">@' + backData.replyName + '</a> ';
                }

                var html = `
                    <div class="list-info" data-id="${backData.userForumReplyId}">                                    
                        <input type="text" value="${backData.userForumReplyId}" data-userforumid="${backData.forumId}" data-level="${replyData.replyLevel}" data-replypid="${backData.userForumReplyId}" class="hide">
                        <p><a href="#">${backData.createPeopleName}：</a>${replyName}${replyData.replyContent}</p>
                        <div class="list-time">${time}</div>
                        <div class="list-action">
                            <a href="Javascript:void(0);" class="list-reply-btn"><i class="mdi mdi-message-text-outline"></i>回复</a>
                            <a href="#!" class="delete" onclick="deleteReply(this, '${backData.userForumReplyId}');"><i class="mdi mdi-delete-variant"></i>删除</a>
                            <!--<a href="Javascript:void(0);"><i class="mdi mdi-thumb-up-outline"></i><span>6</span></a>-->
                        </div>
                    </div>
                `;
                listReplyBox.prepend(html);

                $('#replyModal').modal('hide');
                $('#replyModal input, #replyModal textarea').val('');
            } else {
                promptInfo('错误代码：' + data.code);
            }
        },
        error: function (res) {
            promptInfo('数据请求失败，请重试！(' + res + ')');
        }
    })
}

/**
 * 功能：表情回显
 * */
function emojiShow(obj) {
    $(obj).emojiParse({
        basePath: '../../images/emoji',
        icons: emojiLists
    });
}

/**
 * 功能：点赞、收藏、转发
 * 参数：userForumId-论坛id  likeType-喜欢类型 1点赞 2收藏 3分享
 * */
function messageAction(likeType, id, url, fun) {
    var data = {
        likeType,
        userForumId: id,
    }
    $.ajax({
        url,
        type: 'post',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(data),
        success: function (data) {
            if (data.code == '000000') {
                fun && fun();
            } else {
                promptInfo('错误代码：' + data.code);
            }
        },
        error: function (res) {
            promptInfo('数据请求失败，请重试！(' + res + ')');
        }
    })
}
function queryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort;                  //排序列名
    params.sortOrder = params.order;                //排序方式

    params.userForumId =  '';        // 论坛id
    params.forumTitle =  '';         // 标题（根据标题查询）
    params.forumContent =  '';       // 内容（根据内容查询，不知有没有这个功能先预留了）
    params.userName =  '';           // 用户名（根据用户名查询）
    params.accountId =  '';          // 用户id（查询用户所有的论坛，个人主页时调用）

    return params;
}

/**
 * 功能：优秀话题
 * */
function goodTopic() {
    $.ajax({
        url: '/userForum/selectGodTopic',
        type: 'post',
        dataType: "json",
        success: function (data) {
            if (data.code == '000000') {
                var topicData = data.data;
                var listDom = '';
                for (let i = 0; i < topicData.length; i++) {
                    if (i > 7) {
                        break;
                    }
                    listDom += '<li><em>' + (i + 1) + '</em><a href="#">' + topicData[i].topicName + '</a><span>' + topicData[i].discussNumber + '</span></li>';
                }
                $('#topicList').html(listDom);
            } else {
                promptInfo('错误代码：' + data.code);
            }
        },
        error: function (res) {
            promptInfo('数据请求失败，请重试！(' + res + ')');
        }
    })
}

/**
 * 功能：热力搜索
 * */
function mostSearch() {
    $.ajax({
        url: '/userForum/selectMostSearch',
        type: 'post',
        dataType: "json",
        success: function (data) {
            if (data.code == '000000') {
                var mostData = data.data;
                // console.log(mostData);
                var listDom = '';
                for (let i = 0; i < mostData.length; i++) {
                    if (i > 7) {
                        break;
                    }
                    listDom += '<li><em>' + (i + 1) + '</em><a href="#">' + mostData[i].searchName + '</a><span></span></li>';
                }
                $('#topheatList').html(listDom);
            } else {
                promptInfo('错误代码：' + data.code);
            }
        },
        error: function (res) {
            promptInfo('数据请求失败，请重试！(' + res + ')');
        }
    })
}

/**
 * 功能：删除帖子
 * */
function deleteForum(el, userForumId) {
    var forumCard = $(el).parents('.forum-card');
    $.alert({
        title: '温馨提示',
        content: '确定要删除此条信息吗？',
        buttons: {
            cancel: {
                text: '取消',
                btnClass: 'btn-link',
            },
            confirm: {
                text: '确认',
                btnClass: 'btn-warning',
                scrollToPreviousElement: false,
                scrollToPreviousElementAnimate: false,
                action: function () {
                    $.ajax({
                        url: '/userForum/delUserForum',
                        type: 'post',
                        dataType: "json",
                        data: {
                            userForumId
                        },
                        success: function (data) {
                            if (data.code == '000000') {
                                forumCard.slideUp(120, function () {
                                    $(this).remove();
                                })
                            } else {
                                promptInfo('错误代码：' + data.code);
                            }
                        },
                        error: function (res) {
                            promptInfo('数据请求失败，请重试！(' + res + ')');
                        }
                    })
                }
            }
        }
    });
}

/**
 * 功能：删除评论
 * */
function deleteReply(el, userForumReplyId, flag) {
    var replyDom;
    if (flag) {
        replyDom = $('.list[data-id="' + userForumReplyId + '"]');
    } else {
        replyDom = $('.list-info[data-id="' + userForumReplyId + '"]');
    }
    $.alert({
        title: '温馨提示',
        content: '确定要删除此条评论吗？',
        buttons: {
            cancel: {
                text: '取消',
                btnClass: 'btn-link',
            },
            confirm: {
                text: '确认',
                btnClass: 'btn-warning',
                scrollToPreviousElement: false,
                scrollToPreviousElementAnimate: false,
                action: function () {
                    $.ajax({
                        url: '/userForumReply/delForumReply',
                        type: 'post',
                        dataType: "json",
                        data: {
                            userForumReplyId
                        },
                        success: function (data) {
                            if (data.code == '000000') {
                                replyDom.slideUp(120, function () {
                                    $(this).remove();
                                })
                            } else {
                                promptInfo('错误代码：' + data.code);
                            }
                        },
                        error: function (res) {
                            promptInfo('数据请求失败，请重试！(' + res + ')');
                        }
                    })
                }
            }
        }
    });
}

/**
 * 功能：
 * */
function f() {
    $.ajax({
        url: '',
        type: 'get',
        dataType: "json",
        success: function (data) {
            if (data.code == '000000') {

            } else {
                promptInfo('错误代码：' + data.code);
            }
        },
        error: function (res) {
            promptInfo('数据请求失败，请重试！(' + res + ')');
        }
    })
}


































/**
 * 功能：提示信息
 */
function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                scrollToPreviousElement: false,
                scrollToPreviousElementAnimate: false,
            }
        }
    });
}